<template>
  <el-dialog title="批量编辑采购发票" :visible.sync="dialogVisible" width="1300px" :close-on-click-modal="false"
    :modal-append-to-body="false">
    <div>
      <el-form :model="filterData" ref="filterForm" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="付款单号:">
              <el-input placeholder="付款单号" v-model="filterData.reqcode" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品名称:">
              <el-input placeholder="商品名称" v-model="filterData.title" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商:">
              <el-input placeholder="供应商" v-model="filterData.supname" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="el-icon-search" @click="handlerFilter">搜索</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="width: 100%;"></el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="搜索结果">
              <div style="height:300px; overflow-y: auto; border:1px solid #EEEEEE; padding:2px">
                <el-table :data="tableData" ref="listtable" border height="100%" @select="handleSelect" @select-all="handleSelect">
                  <el-table-column type="selection" disabled fixed="left" align="center"></el-table-column>
                  <el-table-column label="序号" type="index" fixed="left" align="center"></el-table-column>
                  <el-table-column label="付款单号" prop="reqcode" width="100px"></el-table-column>
                  <el-table-column label="供应商" prop="supname" width="150px" align="center" show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="产品名称" prop="title" width="150px" show-overflow-tooltip></el-table-column>
                  <el-table-column label="品牌" prop="brand" show-overflow-tooltip width="60px"></el-table-column>
                  <el-table-column label="规格" prop="model" show-overflow-tooltip width="60px"></el-table-column>
                  <el-table-column label="单位" prop="unit" width="50px" show-overflow-tooltip align="center">
                  </el-table-column>
                  <el-table-column label="数量" prop="count" width="50px" align="center"></el-table-column>
                  <el-table-column label="单价" prop="price" width="110px"></el-table-column>
                  <el-table-column label="小计" prop="total" width="110px"></el-table-column>
                  <el-table-column label="开票发票" prop="tickettype" width="120px">
                    <template v-slot="scope">
                      {{scope.row.tickettype}}({{scope.row.ticketrate}})
                    </template>
                  </el-table-column>

                  <el-table-column label="开票金额" prop="ticket_rmb" width="120px" align="center">
                    <template v-slot="scope">
                      <div v-if="scope.row.checked">
                        <el-input v-model="scope.row.ticket_rmb" @change="handleRecalculateRmb" placeholder="开票金额">
                        </el-input>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="发票号码" prop="ticket_sn" width="150px" align="center">
                    <template v-slot="scope">
                      <div v-if="scope.row.checked">
                        {{scope.row.ticket_sn}}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="开票日期" prop="ticket_date" width="150px" align="center">
                    <template v-slot="scope">
                      <div v-if="scope.row.checked">
                        {{scope.row.ticket_date}}
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="是否核销" prop="ticket_ok" width="150px" align="center">
                    <template v-slot="scope">
                      <div v-if="scope.row.checked">
                        <el-checkbox label="已核销" :checked="scope.row.ticket_ok==1? true:false"  v-model="scope.row.ticket_ok"></el-checkbox>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div style="display: flex;">
                <div style="width: 150px;">应收票额: {{sumTicketRmb1.toFixed(4)}}</div>
                <div style="width: 150px;">实收票额: {{sumTicketRmb2.toFixed(4)}}</div>
                <div style="width: 150px; color: #FF0000;" v-if="Math.abs(sumTicketRmb2-sumTicketRmb1)>0">票额差:
                  {{(sumTicketRmb2-sumTicketRmb1).toFixed(4)}}
                </div>
                <div style="flex: 1;text-align: right; padding-right: 10;">
                    <el-pagination class="pagination" prev-text="上一页" next-text="下一页" background
                      layout=" prev, pager, next,sizes,total" :page-sizes="[25, 50, 80]" :total="numrows" :page-size="pagesize"
                      :current-page="curpage" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form :model="formData" ref="formData" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="开票日期:" prop="ticket_date">
              <el-date-picker type="date" v-model="formData.ticket_date" value-format="yyyy-MM-dd" placeholder="开票日期"
                @change="handleTicketDateChanged" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发票号码:" prop="ticket_sn">
              <el-input v-model="formData.ticket_sn" placeholder="发票号码" @change="handleTicketSnChanged"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="上传发票:">
              <el-upload list-type="picture-card" ref="upload" :file-list="uploadConfig.imgList"
                :action="uploadConfig.action" :headers="uploadConfig.headers" :accept="uploadConfig.accept"
                :limit="uploadConfig.limit" :on-change="handleChange" :auto-upload="false" :on-remove="handleRemove"
                :on-exceed="handleLimit" multiple :before-remove="handleBeforRemove" :on-preview="handlePreviewPreview">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="开票备注">
              <el-input type="textarea" :rows="3" placeholder="开票备注信息" v-model="formData.ticket_memo"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="medium">取消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        index:-1,
        filterData: {
          reqcode: '',
          title: '',
          supname: ''
        },
        formData: {
          ticket_sn: '',
          ticket_date: '',
          ticket_memo:''
        },
        sumTicketRmb1: 0,
        sumTicketRmb2: 0,
        tableData: [],
        curpage: 1,
        pagesize: 20,
        numrows:1,
        dialogVisible: false,
        //文件上传相关变量
        uploadConfig: {
          //文件上传相关参数
          accept: '.jpg,.jpeg,.png,.pdf',
          limit: 5,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          removeids: [], //要删除的id
          action: ""
        }
      }
    },
    methods: {
      initData() {
        this.index=-1;
        this.loadDataList();
      },
      initEdit(index,list){
        console.log(index,list);
        this.index=index;
        this.curpage=1;
        this.formData.ticket_sn=list.ticket_sn;
        this.formData.ticket_date=list.ticket_date;
        this.formData.ticket_ok=parseInt(list.ticket_ok)?true:false;
        this.tableData = [list];
        this.$nextTick(()=>{
             this.$refs.listtable.toggleAllSelection()
          })
       },
      loadDataList() { //加载未核销发票的清单
        const params = {
          reqcode: this.filterData.reqcode,
          title: this.filterData.title,
          supname: this.filterData.supname,
          curpage: this.curpage,
          pagesize: this.pagesize
        }

        this.axios.post("api/admin/buydetail/unticketlist", params).then(res => {
          if (res.status == 200 && res.data.code) {
            this.tableData = res.data.list;
          }
        })
      },
      handlerFilter() {
        this.curpage = 1;
        this.loadDataList();
      },
      handleSelect(selection) {
        for (var i = 0; i < this.tableData.length; i++) {
          this.tableData[i].checked = false;
        }
        this.sumTicketRmb1 = 0;
        this.sumTicketRmb2 = 0;
        for (var i = 0; i < selection.length; i++) {
          var index = this.tableData.indexOf(selection[i]);
          this.tableData[index].checked = true;
          this.sumTicketRmb1 += parseFloat(this.tableData[index].total);
          this.sumTicketRmb2 += parseFloat(this.tableData[index].ticket_rmb);
        }
      },
      handleRecalculateRmb() {
        this.sumTicketRmb1 = 0;
        this.sumTicketRmb2 = 0;
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].checked) {
            this.sumTicketRmb1 += parseFloat(this.tableData[i].total);
            this.sumTicketRmb2 += parseFloat(this.tableData[i].ticket_rmb);
          }
        }
      },
      handleTicketSnChanged() {
        console.log(this.formData.ticket_sn);
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].checked) {
            this.tableData[i].ticket_sn = this.formData.ticket_sn;
          }
        }
      },
      handleTicketDateChanged() {
        console.log(this.formData.ticket_date);
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].checked) {
            this.tableData[i].ticket_date = this.formData.ticket_date;
          }
        }
      },
      handleSave() {
        //检查是否都填写完成
        this.$refs.formData.validate(ok => {
           if(ok){
             //检测选中记录
            const details=[];
            for (var i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].checked) {
                if(this.tableData[i].ticket_rmb==""){
                    this.$message.error({message:'开票金额不能为空!',type:'error',showClose:true});
                    return;
                }else{
                  details.push(this.tableData[i].did+"|"+this.tableData[i].ticket_rmb+"|"+this.tableData[i].ticket_ok);
                }
              }
            }
            if(details.length<=0){
              this.$message.error({message:"录入的开票明细不能为空项!",type:'error',showClose:true});
            }

            var fd=new FormData();
            fd.append("ticket_sn",this.formData.ticket_sn);
            fd.append("ticket_date",this.formData.ticket_date?"":this.formData.ticket_date);
            fd.append("details",details.join(","));
            fd.append("rids",this.uploadConfig.removeids.join(","));

            //附件上传
            let fid = 0;
            this.uploadConfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("file" + fid, file.raw);
                fid++;
              }
            });

            this.$axiosUploader.post("api/admin/buydetail/update_multiticket",fd).then(res=>{

            })

           }
        })



      },
      /***资质附件**/
      handleChange: function(file, list) {
        console.log(file,list);
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png', "pdf"];
        var sizeok = file.size / 1024 / 1024 < 50;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.uploadConfig.fileList.splice(this.uploadConfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过50M");
          this.uploadConfig.fileList.splice(this.uploadConfig.fileList.length - 1, 1);
          return;
        }
        this.uploadConfig.fileList = list;
      },
      handleBeforRemove: function(file, FileList) {
        return this.$confirm("此操作将会删除当前附件吗，是否继续?", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      },
      handleRemove: function(file) {
        if (file.id) { //如果存储 id即为已经上传好的图片
          this.uploadConfig.removeids.push(file.id);
        }
      },
      handleLimit: function() {
        this.$message.warning("最多可上传" + this.uploadConfig.limit + "个文件");

      },
      handlePreviewPreview: function(file) {

      }
    }
  }
</script>

<style>
</style>
